package com.nami.message.acl.repository.inbox;

import cn.hutool.core.collection.CollUtil;
import com.nami.message.domain.model.pmsg.PChatMsgModel;
import com.nami.message.domain.model.gmsg.GrpMsgDomain;
import com.nami.message.domain.repository.InBoxRepository;
import com.nami.message.acl.repository.inbox.convertor.Model2InBoxDOConvertor;
import com.nami.message.core.mybatis.mapper.InboxMsgsMapper;
import com.nami.message.core.mybatis.dataobject.inbox.InboxMsgsDO;
import com.nami.message.util.constants.GrpConfigConst;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class InBoxRepositoryImpl implements InBoxRepository {

    private final InboxMsgsMapper inboxMsgsMapper;

    @Override
    public boolean add(PChatMsgModel msgModel) {
        InboxMsgsDO inboxMsgsDO = Model2InBoxDOConvertor.toDO(msgModel);
//        InboxMsgsDO inboxMsgsDO = InBoxConvert.INSTANCE.convert(msgModel);
        int insert = inboxMsgsMapper.insert(inboxMsgsDO);
        if (insert < 1) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    @Override
    public void addGrpMsg(GrpMsgDomain domain) {
        // 收件箱
        if (CollUtil.isNotEmpty(domain.getReceiverIds())
            && domain.getReceiverIds().size() < GrpConfigConst._MAX_INBOX_MEMBERS) {
            List<InboxMsgsDO> inboxMsgsList = new ArrayList<>(domain.getReceiverIds().size());
            InboxMsgsDO inboxItem;
            for (String receiverId : domain.getReceiverIds()) {
                if (receiverId.equals(domain.getSenderId())) {
                    continue;
                }
                inboxItem = new InboxMsgsDO();
                inboxItem.setMsgId(domain.getMessageId());
                inboxItem.setUserId(receiverId);
                inboxItem.setTargetId(domain.getCid());
                inboxItem.setAppKey(domain.getAppKey());
                inboxItem.setPayload(domain.getPayload());
                inboxItem.setPayloadType(domain.getPayloadType());
                inboxItem.setSendTime(domain.getSendTime());
                inboxItem.setConverType(2); // c2g
                inboxMsgsList.add(inboxItem);
            }
            // TODO 删除，
            // 统一在消息分发时候，进行添加。不在此处处理
            inboxMsgsMapper.insert(inboxMsgsList);
        }
    }

}
